package cn.wwk.notification.search.service.iml;

import cn.wwk.notification.common.domain.Location;
import cn.wwk.notification.common.domain.User;
import cn.wwk.notification.common.result.CodeMsg;
import cn.wwk.notification.common.result.Result;
import cn.wwk.notification.feign.clients.LocationClient;
import cn.wwk.notification.feign.clients.UserClient;
import cn.wwk.notification.search.doc.UserDoc;
import cn.wwk.notification.search.service.UserDocService;
import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * @author wwk
 */
@Service
public class UserDocServiceImpl implements UserDocService {

    @Resource
    private RestHighLevelClient client;

    @Resource
    private UserClient userClient;

    @Resource
    private LocationClient locationClient;

    /**
     * Bulk add to index result.
     *
     * @return the result
     */
    @Override
    public Result bulkAddToIndex() throws IOException {
        // 0.查询数据库中的所有用户信息
        Result<List<User>> all = userClient.getAll();
        List<User> users = all.getData();
        // 1.创建Request
        BulkRequest request = new BulkRequest();
        // 2.准备参数，添加多个新增的Request
        for (User user : users) {
            //2.0根据用户中的地点id，查询对应的地点对象
            String lid = user.getLid();
            Result<Location> result = locationClient.getById(lid);
            Location location = result.getData();
            // 2.1.转换为文档类型HotelDoc
            UserDoc userDoc = new UserDoc(user,location);
            // 2.2.创建新增文档的Request对象
            request.add(new IndexRequest("user")
                    .id(userDoc.getId().toString())
                    .source(JSON.toJSONString(userDoc), XContentType.JSON));
        }
        // 3.发送请求
        client.bulk(request, RequestOptions.DEFAULT);
        return Result.success(CodeMsg.SUCCESS);
    }
}
